package com.sloera.stream;

import java.util.*;

/**
 * @author sloera
 * @create 2020/8/2
 */
public class streamTemp {
    public static void main(String[] args) {
        hashMap();

        parallelMap();
    }

    /**
     * hasMap线程不安全，加 parallel 会导致输出结果不确定
     */
    public static void hashMap() {
        List<String> props = Arrays.asList("a=1", "b=2", "c=3", "b=4");
        Map<String, String> map = props.stream()
                //.parallel()  //加上parallel() 和不加结果不一样
                .map(kv -> {
                    String[] ss = kv.split("=");
                    return Collections.singletonMap(ss[0], ss[1]);
                }).reduce(new HashMap<>(), (m, kv) -> {
                    m.putAll(kv);
                    return m;
                });
        map.forEach((k, v) -> {
            System.out.println(k + " = " + v);
        });
    }


    /**
     * 给 HashMap 加锁
     */
    public static void parallelMap() {
        List<String> props = Arrays.asList("a=1", "b=2", "c=3", "b=4");
        Map<String, String> map = props.stream().parallel()  //加上parallel() 和不加结果不一样
                .map(kv -> {
                    String[] ss = kv.split("=");
                    return Collections.singletonMap(ss[0], ss[1]);
                }).reduce(Collections.synchronizedMap(new HashMap<>()), (m, kv) -> {
                    m.putAll(kv);
                    return m;
                });
        map.forEach((k, v) -> {
            System.out.println(k + " = " + v);
        });
    }
}
